<template>
  <div class="chat-container">
    <div class="chat-header">
      <h2>{{ roomInfo.name || '聊天房间' }}</h2>
      <div class="header-info">
        <span class="ws-status" :class="wsStatus">{{ wsStatus }}</span>
        <button @click="testReadStatus" class="test-read-btn">测试已读</button>
        <button @click="leaveRoom" class="leave-btn">离开房间</button>
      </div>
    </div>
    
    <div class="chat-messages" 
         @scroll="handleScroll"
         @touchstart="handleTouchStart"
         @touchmove="handleTouchMove"
         @touchend="handleTouchEnd">
      <div v-if="isPullingToLoad && !loadingMore" class="pull-to-load-hint">
        <i class="fas fa-arrow-down"></i>
        <span>继续下拉加载历史消息</span>
      </div>
      <div v-if="loadingMore" class="loading-more">
        <i class="fas fa-spinner fa-spin"></i>
        <span>正在加载历史消息...</span>
      </div>
      <div v-else-if="!hasMoreMessages" class="no-more-messages">没有更多消息了</div>
      <div 
        v-for="(group, groupIndex) in groupedMessages" 
        :key="group.date"
        class="message-group"
      >
        <div class="date-divider">
          <span class="date-text">{{ group.date }}</span>
        </div>
                 <div 
           v-for="msg in group.messages" 
           :key="msg.id" 
           :class="['message-item', msg.user_id === userStore.userId ? 'self-message' : 'other-message']"
           @click="handleMessageClick(msg)"
         >
           <div v-if="msg.user_id !== userStore.userId" class="message-avatar">{{ msg.userAvatar }}</div>
           <div class="message-content">
            <div class="message-user">{{ msg.username }}</div>
            <div class="message-text">{{ msg.content }}</div>
                         <div class="message-time">{{ formatTime(msg.timestamp) }}</div>
             <div v-if="msg.status === 'sending'" class="message-status sending">
               <i class="fas fa-spinner fa-spin"></i>
               <span>发送中...</span>
             </div>
             <div v-else-if="msg.status === 'failed'" class="message-status failed">
               <i class="fas fa-exclamation-circle"></i>
               <span>发送失败</span>
               <button class="retry-btn" @click="retrySendMessage(msg)">重试</button>
             </div>
             
             <!-- 未读状态指示器 -->
             <div v-if="shouldShowReadStatus(msg)" class="unread-indicator">
               <div v-if="roomUserCount > 1" class="read-dot"></div>
               <div v-else class="unread-dot"></div>
               <span class="read-status-text">{{ getReadStatusText(msg) }}</span>
             </div>
           </div>
           <div v-if="msg.user_id === userStore.userId" class="message-avatar">{{ msg.userAvatar }}</div>
         </div>
      </div>
    </div>

    <div class="chat-input">
      <textarea
        v-model="inputMessage"
        placeholder="输入消息..."
        @keyup.enter="sendMessage"
      ></textarea>
      <button @click="sendMessage" class="send-btn">发送</button>
    </div>
  </div>
  
  <!-- 滚动到底部按钮 - 放在容器外部 -->
  <button 
    v-if="showScrollToBottom" 
    @click="scrollToBottom" 
    class="scroll-to-bottom-btn"
    title="滚动到底部">
    <i class="fas fa-arrow-down"></i>
  </button>
</template>

<script setup>
import { ref, onMounted, onUnmounted, computed, nextTick } from 'vue'
import { roomApi } from '@/api'
import { useUserStore } from '@/stores/user'
import { handleApiError } from '@/utils/error-handler'
import { formatTime } from '@/utils/date-utils'
import { CONFIG } from '@/utils/config'
import { checkLoginStatus, initializeUserStore } from '@/utils/auth'
import { createChatConnection, closeAllConnections } from '@/utils/websocket-manager'

uni.showToast({ title: '进入聊天页面', icon: 'none', duration: 1000 })
// 状态管理
const userStore = useUserStore()

// 房间信息和消息
const roomId = ref(parseInt(uni.getStorageSync('roomId')) || 0)
const roomInfo = ref({})
const messages = ref([])
const inputMessage = ref('')
let ws = null

// WebSocket管理器
let wsManager = null

// 未读消息计数
const unreadCount = ref(0)

// 消息历史加载状态
const loadingMore = ref(false)
const hasMoreMessages = ref(true)
const wsStatus = ref('连接中')
const pullToLoadThreshold = ref(0) // 下拉加载阈值
const isPullingToLoad = ref(false) // 是否正在下拉加载
const showScrollToBottom = ref(false) // 是否显示滚动到底部按钮

// 消息已读状态管理 - 简化版本
const messageReadStatus = ref(new Map()) // 本地已读状态
const roomUserCount = ref(0) // 房间用户数量（从服务器获取）

// 计算属性：按日期分组的消息
const groupedMessages = computed(() => {
  const groups = {}
  
  messages.value.forEach(message => {
    // 格式化日期为 YYYY-MM-DD
    const date = formatDate(new Date(message.timestamp))
    
    if (!groups[date]) {
      groups[date] = {
        date: date,
        messages: []
      }
    }
    
    groups[date].messages.push(message)
  })
  
  // 转换为数组并按日期排序
  return Object.values(groups).sort((a, b) => {
    return new Date(a.date) - new Date(b.date)
  })
})

// 辅助函数：格式化日期
function formatDate(date) {
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  return `${year}-${month}-${day}`
}

// 获取房间信息
const getRoomInfo = async () => {
  try {
    const data = await roomApi.getRoomInfo(roomId.value)
    roomInfo.value = data
    
    // 从房间信息中获取用户数量
    if (data.user_count !== undefined) {
      roomUserCount.value = data.user_count
      console.log('从房间信息获取用户数量:', roomUserCount.value)
    }
    
  } catch (error) {
    handleApiError(error, '获取房间信息')
  }
}

// 获取消息历史
const getMessageHistory = async (page = 1, pageSize = 20) => {
  if (loadingMore.value || !hasMoreMessages.value) return
  
  try {
    loadingMore.value = true
    const res = await roomApi.getMessageHistory(roomId.value, page, pageSize)
    
    if (res.data && res.data.length > 0) {
      // 过滤已存在的消息（去重）
      const newMessages = res.data.filter(
        newMsg => !messages.value.some(existingMsg => existingMsg.id === newMsg.id)
      )
      
      if (newMessages.length > 0) {
        // 将新消息添加到消息列表开头
        messages.value.unshift(...newMessages)
        
        // 对消息列表按时间戳排序
        messages.value.sort((a, b) => new Date(a.timestamp) - new Date(b.timestamp))
      } else {
        // 如果没有新消息，说明已加载完所有历史消息
        hasMoreMessages.value = false
      }
    } else {
      // 没有更多消息
      hasMoreMessages.value = true
    }
  } catch (error) {
    handleApiError(error, '获取消息历史')
  } finally {
    loadingMore.value = false
  }
}

// 处理滚动事件
const handleScroll = (event) => {
  const { scrollTop, scrollHeight, clientHeight } = event.target
  
  // 当滚动到顶部时，开始检测下拉加载
  if (scrollTop === 0 && !loadingMore.value && hasMoreMessages.value) {
    if (!isPullingToLoad.value) {
      isPullingToLoad.value = true
      pullToLoadThreshold.value = 0
      
      // 显示下拉提示
      uni.showToast({ 
        title: '继续下拉加载历史消息', 
        icon: 'none', 
        duration: 1500 
      })
    }
  }
  
  // 当滚动到底部时，重置未读消息计数并隐藏滚动按钮
  if (scrollTop + clientHeight >= scrollHeight - 5) {
    showScrollToBottom.value = false
  } else {
    // 如果不在底部，显示滚动按钮
    showScrollToBottom.value = true
  }
}

// 处理触摸事件 - 实现下拉加载确认机制
const handleTouchStart = (event) => {
  // 检查是否在顶部
  const scrollElement = event.target.closest('.chat-messages')
  if (scrollElement && scrollElement.scrollTop === 0) {
    if (isPullingToLoad.value) {
      pullToLoadThreshold.value = event.touches[0].clientY
    }
  }
}

const handleTouchMove = (event) => {
  if (isPullingToLoad.value && pullToLoadThreshold.value > 0) {
    const currentY = event.touches[0].clientY
    const pullDistance = pullToLoadThreshold.value - currentY
    
    // 如果下拉距离超过50px，触发加载
    if (pullDistance > 50) {
      loadMoreMessages()
      isPullingToLoad.value = false
      pullToLoadThreshold.value = 0
      
      // 显示加载提示
      uni.showToast({ 
        title: '正在加载历史消息...', 
        icon: 'loading', 
        duration: 1000 
      })
    }
  }
}

const handleTouchEnd = () => {
  // 重置下拉状态
  if (isPullingToLoad.value) {
    setTimeout(() => {
      isPullingToLoad.value = false
      pullToLoadThreshold.value = 0
    }, 1000)
  }
}

// 重置未读消息计数
const resetUnreadCount = () => {
  if (unreadCount.value > 0) {
    unreadCount.value = 0
  }
}

// 标记消息为已读 - 简化版本
const markMessageAsRead = (messageId) => {
  // 安全检查
  if (!messageId || messageId === 'undefined' || messageId === undefined) {
    console.warn('无效的消息ID:', messageId)
    return
  }
  
  if (!messageReadStatus.value.has(messageId)) {
    messageReadStatus.value.set(messageId, {
      isRead: true,
      readTime: Date.now(),
      readBy: userStore.userId
    })
    
    console.log('标记消息为已读:', messageId)
  } else {
    console.log('消息已经标记为已读:', messageId)
  }
}

// 标记所有消息为已读（用户进入房间时调用）
const markAllMessagesAsRead = () => {
  messages.value.forEach(msg => {
    // 安全检查
    if (msg.id && msg.id !== 'undefined' && msg.id !== undefined) {
      if (!messageReadStatus.value.has(msg.id)) {
        messageReadStatus.value.set(msg.id, {
          isRead: true,
          readTime: Date.now(),
          readBy: userStore.userId
        })
      }
    } else {
      console.warn('历史消息ID无效:', msg.id)
    }
  })
  
  console.log('用户进入房间，标记所有消息为已读')
  
  // 发送已读回执到服务器
  if (wsManager && wsManager.getConnected()) {
    const readMessage = {
      type: 10, // MessageTypeRead
      user_id: String(userStore.userId),
      room_id: String(roomId.value),
      content: 'all' // 表示已读所有消息
    }
    
    wsManager.send(readMessage)
    console.log('发送已读所有消息回执')
  }
}

// 检查消息是否已读
const isMessageRead = (messageId) => {
  return messageReadStatus.value.get(messageId)?.isRead || false
}

// 是否应该显示已读状态（仅对发送者显示自己的消息状态）
const shouldShowReadStatus = (message) => {
  return message.user_id === userStore.userId
}

// 获取已读人数显示文本（排除自己）
const getReadStatusText = (message) => {
  if (message.user_id === userStore.userId) {
    // 安全检查：确保roomUserCount是有效数字
    const totalUsers = parseInt(roomUserCount.value) || 0
    const otherUsersCount = Math.max(0, totalUsers - 1) // 排除自己，确保不为负数
    return otherUsersCount > 0 ? `${otherUsersCount}人已读` : '未读'
  }
  return ''
}

// 滚动到底部
const scrollToBottom = () => {
  // 使用nextTick确保DOM更新完成
  nextTick(() => {
    const messagesContainer = document.querySelector('.chat-messages')
    if (messagesContainer) {
      // 使用平滑滚动
      messagesContainer.scrollTo({
        top: messagesContainer.scrollHeight,
        behavior: 'smooth'
      })
    }
  })
}

// 加载更多消息
const loadMoreMessages = () => {
  // 计算当前页码
  const currentPage = Math.ceil(messages.value.length / 20) + 1
  getMessageHistory(currentPage, 20)
}

// 发送消息
const sendMessage = async () => {
  if (!inputMessage.value.trim()) return

  // 生成临时消息ID
  const tempId = `temp_${Date.now()}`
  
  // 先添加到本地显示（发送中状态）
  const tempMessage = {
    id: tempId,
    user_id: userStore.userId,
    username: userStore.userName,
    content: inputMessage.value,
    timestamp: new Date().getTime(),
    userAvatar: userStore.avatar || '默认头像',
    status: 'sending' // 发送中状态
  }
  
  messages.value.push(tempMessage)
  const messageIndex = messages.value.length - 1
  
  // 清空输入框
  const messageContent = inputMessage.value
  inputMessage.value = ''

  try {
    // 通过WebSocket发送消息
    if (wsManager && wsManager.getConnected()) {
      const message = {
        type: 3, // MessageTypeText
        user_id: String(userStore.userId),
        user_name: userStore.userName,
        content: messageContent,
        time: Math.floor(Date.now() / 1000),
        room_id: String(roomId.value)
      }
      
      if (wsManager.send(message)) {
        // 更新消息状态为已发送
        messages.value[messageIndex].status = 'sent'
        
        // 发送者立即标记自己的消息为已读
        markMessageAsRead(tempId)
        
        // 滚动到底部
        scrollToBottom()
      } else {
        // 更新消息状态为发送失败
        messages.value[messageIndex].status = 'failed'
      }
    } else {
      // WebSocket未连接，使用HTTP API
      const message = {
        roomId: roomId.value,
        content: messageContent,
        userId: userStore.userId,
        username: userStore.userName,
        userAvatar: userStore.avatar || '默认头像'
      }

      await roomApi.sendMessage(roomId.value, message)
      
      // 更新消息状态为已发送
      messages.value[messageIndex].status = 'sent'
      
      // 发送者立即标记自己的消息为已读
      markMessageAsRead(tempId)
      
      // 滚动到底部
      scrollToBottom()
    }
  } catch (error) {
    // 更新消息状态为发送失败
    messages.value[messageIndex].status = 'failed'
    handleApiError(error, '发送消息')
  }
}

// 离开房间
const leaveRoom = async () => {
  try {
    await roomApi.leaveRoom(roomId.value)
    uni.navigateTo({ url: '/pages/room-list/room-list' })
  } catch (error) {
    handleApiError(error, '离开房间')
  }
}

// 重试发送消息
const retrySendMessage = async (message) => {
  // 更新消息状态为发送中
  const messageIndex = messages.value.findIndex(msg => msg.id === message.id)
  if (messageIndex !== -1) {
    messages.value[messageIndex].status = 'sending'
  }
  
  try {
    // 通过WebSocket发送消息
    if (wsManager && wsManager.getConnected()) {
      const retryMessage = {
        type: 3, // MessageTypeText
        user_id: String(message.user_id),
        user_name: message.username,
        content: message.content,
        time: Math.floor(Date.now() / 1000),
        room_id: String(roomId.value)
      }
      
      if (wsManager.send(retryMessage)) {
        // 更新消息状态为已发送
        if (messageIndex !== -1) {
          messages.value[messageIndex].status = 'sent'
        }
      } else {
        // 更新消息状态为发送失败
        if (messageIndex !== -1) {
          messages.value[messageIndex].status = 'failed'
        }
      }
    } else {
      // WebSocket未连接，使用HTTP API
      const retryMessage = {
        roomId: roomId.value,
        content: message.content,
        userId: message.user_id,
        username: message.username,
        userAvatar: message.userAvatar
      }

      await roomApi.sendMessage(roomId.value, retryMessage)
      
      // 更新消息状态为已发送
      if (messageIndex !== -1) {
        messages.value[messageIndex].status = 'sent'
      }
    }
  } catch (error) {
    // 更新消息状态为发送失败
    if (messageIndex !== -1) {
      messages.value[messageIndex].status = 'failed'
    }
    handleApiError(error, '重试发送消息')
  }
}

// 处理消息点击事件
const handleMessageClick = (message) => {
  // 移除手动标记已读功能，改为自动检测
  console.log('点击消息:', message.content)
}

// 测试已读状态
const testReadStatus = () => {
  console.log('=== 房间用户信息 ===')
  console.log('当前用户ID:', userStore.userId)
  console.log('房间用户数量:', roomUserCount.value)
  console.log('已读状态Map大小:', messageReadStatus.value.size)
  
  // 显示消息已读状态详情
  const readMessages = []
  const unreadMessages = []
  const myMessages = []
  const otherMessages = []
  const invalidMessages = []
  const messageSenders = new Set()
  
  messages.value.forEach(msg => {
    // 收集消息发送者
    if (msg.user_id !== userStore.userId) {
      messageSenders.add(msg.user_id)
    }
    
    // 检查消息ID有效性
    if (!msg.id || msg.id === 'undefined' || msg.id === undefined) {
      invalidMessages.push({
        content: msg.content,
        id: msg.id,
        user_id: msg.user_id
      })
      return
    }
    
    if (msg.user_id === userStore.userId) {
      myMessages.push({
        content: msg.content,
        id: msg.id,
        isRead: isMessageRead(msg.id)
      })
    } else {
      otherMessages.push({
        content: msg.content,
        id: msg.id,
        isRead: isMessageRead(msg.id)
      })
    }
    
    if (isMessageRead(msg.id)) {
      readMessages.push(msg.content)
    } else {
      unreadMessages.push(msg.content)
    }
  })
  
  console.log('我的消息:', myMessages)
  console.log('别人的消息:', otherMessages)
  console.log('消息发送者列表:', Array.from(messageSenders))
  console.log('房间用户数量:', roomUserCount.value)
  console.log('无效消息ID:', invalidMessages)
  console.log('已读消息:', readMessages)
  console.log('未读消息:', unreadMessages)
  
  // 显示当前房间用户信息
  uni.showToast({
    title: `房间用户: ${roomUserCount.value}人, 发送者: ${messageSenders.size}人, 已读: ${readMessages.length}条`,
    icon: 'none',
    duration: 3000
  })
}

// 初始化WebSocket连接
const initWebSocket = () => {
  
  wsManager = createChatConnection(roomId.value, {
    onOpen: () => {
      console.log('聊天WebSocket连接成功')
      wsStatus.value = '已连接'
      uni.showToast({ title: '连接成功', icon: 'success', duration: 1000 })
      
      // 用户进入房间，标记所有消息为已读
      markAllMessagesAsRead()
    },
    onJoin: (message) => {
      try {
        uni.showToast({ title: `${message.user_name}加入了房间`, icon: 'none', duration: 1000 })
        
        // 不手动增加用户数量，等待服务器发送准确的用户数量
        console.log('用户加入房间，等待服务器更新用户数量')
      } catch (error) {
        console.error('处理用户加入事件时出错:', error)
      }
    },
    onLeave: (message) => {
      try {
        uni.showToast({ title: `${message.user_name}离开了房间`, icon: 'none', duration: 1000 })
        
        // 不手动减少用户数量，等待服务器发送准确的用户数量
        console.log('用户离开房间，等待服务器更新用户数量')
      } catch (error) {
        console.error('处理用户离开事件时出错:', error)
      }
    },
    onText: (message) => {
      try {
        // 过滤掉自己发送的消息，避免重复显示
        if (message.user_id !== String(userStore.userId)) {
          // 添加发送状态字段
          const newMessage = {
            id: message.id || `received_${Date.now()}`, // 确保有ID
            user_id: message.user_id,
            username: message.user_name,
            content: message.content,
            timestamp: message.time * 1000,
            userAvatar: '默认头像',
            status: 'sent' // 'sending' | 'sent' | 'failed'
          }
          
          messages.value.push(newMessage)
          
          // 增加未读消息计数
          unreadCount.value++
          
          // 自动标记新收到的消息为已读（因为用户看到了）
          if (newMessage.id && newMessage.id !== 'undefined') {
            markMessageAsRead(newMessage.id)
            console.log('收到新消息，标记为已读:', newMessage.id)
          } else {
            console.warn('消息ID无效，无法标记为已读:', newMessage.id)
          }
          
          // 滚动到底部
          scrollToBottom()
        }
      } catch (error) {
        console.error('处理接收消息事件时出错:', error)
      }
    },
    onUserListUpdate: (message) => {
      try {
        // 处理用户列表更新
        console.log('收到用户列表更新:', message)
        // 这里不再需要更新 roomUsers.value，因为 roomUserCount 已经从服务器获取
      } catch (error) {
        console.error('处理用户列表更新事件时出错:', error)
      }
    },
    onRoomUserCount: (message) => {
      // 处理房间人数更新
      console.log('房间人数更新:', message)
      
      try {
        // 支持多种消息格式
        let userCount = null
        
        // 格式1: message.data.user_count
        if (message.data && message.data.user_count !== undefined) {
          userCount = message.data.user_count
        }
        // 格式2: message.user_count
        else if (message.user_count !== undefined) {
          userCount = message.user_count
        }
        // 格式3: message.content (如果是数字)
        else if (message.content && !isNaN(parseInt(message.content))) {
          userCount = parseInt(message.content)
        }
        
        if (userCount !== null) {
          roomUserCount.value = userCount
          console.log('房间用户数量更新:', userCount)
        } else {
          console.warn('无法解析房间用户数量:', message)
        }
      } catch (error) {
        console.error('处理房间用户数量更新时出错:', error)
      }
    },
    onSystem: (message) => {
      try {
        uni.showToast({ title: message.content, icon: 'none', duration: 2000 })
      } catch (error) {
        console.error('处理系统消息事件时出错:', error)
      }
    },
    onClose: (event) => {
      console.log('聊天WebSocket连接关闭:', event)
      wsStatus.value = '已断开'
      console.error(`连接已断开`, 'WebSocket连接')
    },
    onError: (error) => {
      console.error('聊天WebSocket连接错误:', error)
      wsStatus.value = '已断开'
      console.error(error.message, 'WebSocket连接')
      handleApiError(error, 'WebSocket连接')
    },
    onRead: (message) => {
      try {
        // 处理WebSocket接收到的已读状态
        console.log('收到已读状态消息:', message)
        // 这里不需要更新用户列表，因为用户加入/离开会通过onJoin/onLeave处理
      } catch (error) {
        console.error('处理已读状态事件时出错:', error)
      }
    }
  })
  
  wsManager.connect()
}

// 设置消息可见性检测
const setupMessageVisibilityDetection = () => {
  // 使用更简单的滚动检测，避免Intersection Observer的复杂性
  console.log('设置消息可见性检测')
}

// 组件挂载时
onMounted(() => {
  // 添加全局错误处理
  window.addEventListener('error', (event) => {
    console.error('全局错误:', event.error)
    // 防止页面崩溃
    event.preventDefault()
  })
  
  window.addEventListener('unhandledrejection', (event) => {
    console.error('未处理的Promise拒绝:', event.reason)
    // 防止页面崩溃
    event.preventDefault()
  })
  
  // 初始化用户store
  initializeUserStore()
  
  if (!checkLoginStatus()) {
    uni.navigateTo({ url: '/pages/login/login' })
    return
  }

  // 检查是否有房间ID
  if (!roomId.value) {
    uni.showToast({
      title: '请先选择房间',
      icon: 'none',
      duration: 2000
    })
    setTimeout(() => {
      uni.navigateTo({ url: '/pages/room-list/room-list' })
    }, 2000)
    return
  }

  getRoomInfo()
  getMessageHistory()
  initWebSocket()
  
  // 初始化房间用户数量安全检查
  if (roomUserCount.value < 0) {
    roomUserCount.value = 0
    console.warn('房间用户数量异常，已重置为0')
  }
  
  // 初始化后滚动到底部
  setTimeout(() => {
    scrollToBottom()
  }, 500)
  
  // 初始化已读状态管理
  console.log('已读状态管理已初始化')
  console.log('当前未读消息数量:', messageReadStatus.value.size)
  
  // 设置消息可见性检测
  setupMessageVisibilityDetection()
})

// 组件卸载时
onUnmounted(() => {
  if (wsManager) {
    wsManager.close()
  }
  // 关闭所有WebSocket连接
  closeAllConnections()
})
</script>

<style scoped src="./chat.css"></style>